package com.mkbk.controller;

import com.google.gson.Gson;
import com.mkbk.model.User;
import com.mkbk.service.UserService;
import com.mkbk.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();
    private static final Gson gson = new Gson();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        super.service(req, res);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        handleRequest(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        handleRequest(req, res);
    }

    private void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String op = req.getParameter("optionType");
        res.setContentType("application/json;charset=utf-8");
        // 设置跨域
        res.setHeader("Access-Control-Allow-Origin", "*");
        String response;
        if ("register".equals(op)) {
            response = handleRegister(req);
        } else if ("login".equals(op)) {
            response = handleLogin(req);
        } else {
            response = gson.toJson("无效的请求");
        }
        res.getWriter().write(response);
    }

    private String handleRegister(HttpServletRequest req) {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");

        if (!password.equals(confirmPassword)) {
            return gson.toJson("两次密码不一致");
        }

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        userService.register(user);
        return gson.toJson("注册成功");
    }

    private String handleLogin(HttpServletRequest req) {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        User loginUser = userService.login(user);
        if (loginUser != null) {
            return gson.toJson("登录成功");
        } else {
            return gson.toJson("登录失败");
        }
    }
}
